package com.party.web.biz.member;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.dao.read.member.PartnerMemberReadDao;
import com.party.core.model.commune.CMemberRecommend;
import com.party.core.model.member.MemberMgmtQuery;
import com.party.core.model.member.PartnerMember;
import com.party.core.model.system.RoleEnum;
import com.party.core.service.commune.ICMemberRecommendService;
import com.party.core.service.gatherForm.IGatherFormService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.picCloud.CosCloudBizService;
import com.party.core.service.system.ISysRoleService;
import com.party.file.cos.dto.UploadResult;
import com.party.file.cos.meta.InsertOnly;
import com.party.web.biz.system.member.MemberGroupBizService;
import com.party.web.utils.excel.ExportExcel;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 会员管理业务
 * @Author: yangshoukun
 * @Date: 2018/2/22 11:52
 */
@Service
public class MemberMgmtService {

    private String uploadPath = Constant.UPLOAD_EXCEL;

    @Autowired
    private StringJedis stringJedis;

    private static final String REDIS_LIST_KEY = "export_excel_list";

    @Autowired
    private CosCloudBizService cosCloudBizService;

    @Autowired
    private IGatherFormService gatherFormService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private MemberGroupBizService memberGroupBizService;

    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private ICMemberRecommendService memberRecommendService;

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PartnerMemberReadDao partnerMemberReadDao;

    public List<Map<String, Object>> list(MemberMgmtQuery input, String partnerId, Page page) {
        convertDate(input);
        return partnerMemberReadDao.listByPartnerId3(input, partnerId, page);
    }

    public List<Map<String, Object>> webList(MemberMgmtQuery input, String partnerId, Page page) {
        convertDate(input);
        return partnerMemberReadDao.listByPartnerId(input, partnerId, page);
    }

    public List<Map<String, Object>> listMembers(MemberMgmtQuery input, Page page) {
        convertDate(input);
        return partnerMemberReadDao.listMembers(input, page);
    }

    public List<Map<String, Object>> getAllCompanyAddress(List<String> orgIds,String partnerId) {
        return partnerMemberReadDao.getAllCompanyAddress(orgIds,partnerId);
    }

    public List<Map<String, Object>> getAllHomeAddress(List<String> orgIds,String partnerId) {
        return partnerMemberReadDao.getAllHomeAddress(orgIds,partnerId);
    }

    public Long getMemberCount(String partnerId)
    {
        PartnerMember partnerMember = new PartnerMember();
        partnerMember.setPartnerId(partnerId);
        return partnerMemberReadDao.getCount(partnerMember);
    }
    public List<Map<String, Object>> getMemberByPartent(String memberId) {
        return partnerMemberReadDao.listByPartnerId2(memberId);
    }


    private void convertDate(MemberMgmtQuery input) {
        if (null == input || null == input.getTimeType() || 0 ==input.getTimeType()) {
            return;
        }
        Integer timeType = input.getTimeType();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date ed = calendar.getTime(); // 结束时间
        if (input.getTimeType() == 2) { // 本周内
            int day_of_week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            if (day_of_week == 0) {
                day_of_week = 7;
            }
            calendar.add(Calendar.DATE, -day_of_week + 1);
        } else if (input.getTimeType() == 3) { // 本月内
            calendar.set(Calendar.DAY_OF_MONTH, 1);
        } else if (input.getTimeType() == 4) { // 昨天
            calendar.add(Calendar.DATE, -1);
            ed = calendar.getTime();
        }
        Date sd = calendar.getTime(); // 开始时间
        String std = sdf.format(sd) + " 00:00:00";
        input.setCreateStart(std);
        String end = sdf.format(ed) + " 23:59:59";
        input.setCreateEnd(end);
    }


    /**
     * 设置导出内容
     * @param list 输出列表
     * @param exportExcel 导出excel
     * @return 导出excel
     * @Author: huangwuming
     * @Date: 2018/2/27 10:56
     */
    public  ExportExcel setDataList(List<Map<String, Object>> list, ExportExcel exportExcel,
                                    MemberMgmtQuery input,List<String> titles){
        for (Map analyzeOutput : list){
            Row row = exportExcel.addRow();
            String userSerial = (String) analyzeOutput.get("userSerial");
            String nickName = (String) analyzeOutput.get("nickName");
            String sex = (String) analyzeOutput.get("sex");
            String mobile = (String) analyzeOutput.get("mobile");
            String wechatNum = (String) analyzeOutput.get("wechatNum");
            String company = (String) analyzeOutput.get("company");
            String area = (String) analyzeOutput.get("area");
            String job = (String) analyzeOutput.get("job");
            String createTime = (String) analyzeOutput.get("createTime");
            String realname = (String) analyzeOutput.get("realname");

            // row样式
            CellStyle cellStyle = exportExcel.getWb().createCellStyle();

            exportExcel.addCell(row, 0, userSerial, cellStyle);
            exportExcel.addCell(row, 1, nickName, cellStyle);
            exportExcel.addCell(row, 2, sex, cellStyle);
            exportExcel.addCell(row, 3, mobile, cellStyle);
            exportExcel.addCell(row, 4, wechatNum, cellStyle);
            exportExcel.addCell(row, 5, company, cellStyle);
            exportExcel.addCell(row, 6, area, cellStyle);
            exportExcel.addCell(row, 7, job, cellStyle);
            exportExcel.addCell(row, 8, createTime,cellStyle);
            exportExcel.addCell(row, 9, realname,cellStyle);

            if (input.getType().equals(0)) {
                String checkStatusName = "";
                Object tempCheckStatus = analyzeOutput.get("checkStatus");
                if (null != tempCheckStatus) {
                    Integer checkStatus = (Integer) tempCheckStatus;
                    if (new Integer(0).equals(checkStatus)) {
                        checkStatusName = "待审核";
                    } else if (new Integer(1).equals(checkStatus)) {
                        checkStatusName = "审核通过";
                    } else {
                        checkStatusName = "审核拒绝";
                    }
                }
                exportExcel.addCell(row, 10, checkStatusName, cellStyle);
            }

            //自定义表单值
            if (titles != null) {
                Integer column = Integer.valueOf(10);
                for (String title : titles) {
                    String value = (String) analyzeOutput.get(title);
                    column +=1;
                    exportExcel.addCell(row, column, value, cellStyle);
                }
            }

/*            if(input.getType() == 0) {
                exportExcel.addCell(row, 8, projecNum, cellStyle);
                exportExcel.addCell(row, 9, totalMoney, cellStyle);
            }
            if(input.getType() == 1){
                exportExcel.addCell(row, 8, supportMoney,cellStyle);
            }*/
        }
        return exportExcel;
    }
    /**
     * 上传excel
     *
     * @param fileName    文件名
     * @param exportPath  目录
     * @param exportExcel 文件
     * @return
     */
    public synchronized String getExcelPath(String fileName, String exportPath, ExportExcel exportExcel) throws IOException {
        String suffix = DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS");
        if (fileName.indexOf(".xlsx") != -1) {
            fileName = fileName.substring(0, fileName.indexOf(".xlsx")) + '-' + suffix + ".xlsx";
        } else if (fileName.indexOf(".xls") != -1) {
            fileName = fileName.substring(0, fileName.indexOf(".xls")) + '-' + suffix + ".xls";
        }
        try {
            exportPath = String.format(uploadPath, exportPath, fileName);
            InputStream inputStream = exportExcel.newUploadCloud();
            UploadResult uploadResult = cosCloudBizService.uploadFile(inputStream, exportPath, InsertOnly.NO_OVER_WRITE);
            String resourceUrl = uploadResult.getSourceUrl();
            pushRedis(resourceUrl);
            return resourceUrl;
        } catch (Exception e) {
            logger.error("上传Excel到腾讯云异常：cloudFilePath——" + exportPath + "；cloudFileName——" + fileName, e);
        }
        return null;
    }
    public void pushRedis(String resourceUrl) {
        try {
            resourceUrl = URLDecoder.decode(resourceUrl, Constant.UTF_8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        List<Map> mapList = getRedisAll();
        Map<String, Object> map = Maps.newHashMap();
        map.put(resourceUrl, DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN));
        mapList.add(map);
        stringJedis.setValue(REDIS_LIST_KEY, JSONObject.toJSONString(mapList));
    }
    public List<Map> getRedisAll() {
        List<Map> mapList = Lists.newArrayList();
        String result = stringJedis.getValue(REDIS_LIST_KEY);
        if (StringUtils.isNotEmpty(result)) {
            mapList = JSONArray.parseArray(result, Map.class);
        }
        return mapList;
    }




    public Long getMemberCountByOrgIds(List<String> orgIds) {
        return partnerMemberReadDao.getMemberCountByOrgIds(orgIds);
    }

    public boolean hasZxgsPartner(String partnerId,String memberId) {
        boolean result = false;

        boolean b = sysRoleService.hasRole(partnerId, RoleEnum.KNOWING_COMMUNE_ROLE.getCode());
        if (!b) {
            return result;
        } else {
            String xzgsMemberId = memberGroupBizService.getXzgsMemberId();
            HashMap<String, Object> params = Maps.newHashMap();

            List<String> orgIds = memberGroupService.getChild(xzgsMemberId);

            params.put("memberId",memberId);
            params.put("partnerIds",orgIds);
            List<PartnerMember> partners = partnerMemberReadDao.getMemberPartnersTo(params);

            if (partners.size() > 0) {
                result = true;
            } else {
                result = false;
            }
            return result;
        }
    }

    /**
     * 修改分社下的推荐关系到会员的主分社
     * @param partnerMember
     * @return boolean
     */
    public boolean changBindPmIdToMainOrg(PartnerMember partnerMember) {

        String partnerId = partnerMember.getPartnerId();
        String memberId = partnerMember.getMemberId();
        //获取会员主分社
        PartnerMember mainOrg = partnerMemberService.getMainOrg(memberId, partnerId);

        //该会员所邀请的人
        CMemberRecommend cMemberRecommend = new CMemberRecommend();
        cMemberRecommend.setParentId(partnerMember.getId());
        List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend);

        //邀请该会员的人
        CMemberRecommend uMember = new CMemberRecommend();
        uMember.setuId(partnerMember.getId());
        List<CMemberRecommend> uList = memberRecommendService.list(uMember);

        if (list.size() == 0 && uList.size() ==0) {
            return true;
        }

        //修改推荐人parentId
        for (CMemberRecommend tMember : list) {
            //检查又没有相互推荐
            boolean result = checkBindTMember(tMember, mainOrg.getId());
            if (result) {
                tMember.setParentId(mainOrg.getId());
                memberRecommendService.update(tMember);
            }
        }

        //修改被推荐人u_id
        for (CMemberRecommend uMemberRecom : uList) {
            boolean result = checkBindUMember(uMemberRecom, mainOrg.getId());
            if (result) {
                uMemberRecom.setuId(mainOrg.getId());
                memberRecommendService.update(uMemberRecom);
            }
        }

        return true;
    }

    /**
     *  检查是否有相互推荐关系
     * @author shenliuhai
     * @date 2020/1/2 10:52
     * @param memberPmId
     * @param tjMemberPmId
     * @return boolean
     */
    public boolean checkBindTMember(CMemberRecommend memberPmId, String tjMemberPmId) {

        CMemberRecommend newMemberRecommend = new CMemberRecommend();
        newMemberRecommend.setuId(memberPmId.getuId());
        newMemberRecommend.setParentId(tjMemberPmId);
        List<CMemberRecommend> list = memberRecommendService.list(newMemberRecommend);
        if (list.size() == 0) {
            CMemberRecommend cMemberRecommend = new CMemberRecommend();
            cMemberRecommend.setParentId(memberPmId.getParentId());
            cMemberRecommend.setuId(tjMemberPmId);
            List<CMemberRecommend> t_list = memberRecommendService.list(cMemberRecommend);

            if (t_list.size() == 0) {
                return true;
            }
        }

        return false;
    }

    /**
     * 修改被推荐人
     * @author shenliuhai
     * @date 2020/1/2 11:17
     * @param memberPmId
     * @param uMemberPmId
     * @return boolean
     */
    public boolean checkBindUMember(CMemberRecommend memberPmId, String uMemberPmId) {

        CMemberRecommend newMemberRecommend = new CMemberRecommend();
        newMemberRecommend.setuId(uMemberPmId);
        newMemberRecommend.setParentId(memberPmId.getParentId());
        List<CMemberRecommend> list = memberRecommendService.list(newMemberRecommend);
        if (list.size() == 0) {
            CMemberRecommend cMemberRecommend = new CMemberRecommend();
            cMemberRecommend.setParentId(uMemberPmId);
            cMemberRecommend.setuId(memberPmId.getuId());
            List<CMemberRecommend> t_list = memberRecommendService.list(cMemberRecommend);

            if (t_list.size() == 0) {
                return true;
            }
        }

        return false;
    }

}
